﻿using System;
using System.Reflection;
using Core.Model;
using DapperExtensions;
using DapperExtensions.Mapper;
using log4net;

namespace DataServer.Dao
{
    public class DeviceTypeDao : BaseDao<DeviceType>
    {
        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static DeviceTypeMapper _deviceTypeMapper;

        public DeviceTypeDao()
        {
            if (_deviceTypeMapper == null)
            {
                _deviceTypeMapper = new DeviceTypeMapper();
            }
        }

        protected override string GetTableName()
        {
            if (_deviceTypeMapper != null)
                return _deviceTypeMapper.TableName;
            return "device_type";
        }

        public DeviceType GetEntityById(string id)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<DeviceType>(f => f.Id, Operator.Eq, id);
                DeviceType deviceType = result?.Connection.Get<DeviceType>(predicate);
                return deviceType;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

        public DeviceType GetEntityByName(string name)
        {
            ConnectResult result = null;
            try
            {
                result = OpenDbConnection();
                var predicate = Predicates.Field<DeviceType>(f => f.Name, Operator.Eq, name);
                DeviceType deviceType = result?.Connection.Get<DeviceType>(predicate);
                return deviceType;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return null;
            }
            finally
            {
                if (result != null)
                {
                    CloseDbConnection(result.Name);
                }
            }
        }

    }
    public sealed class DeviceTypeMapper : ClassMapper<DeviceType>
    {
        public DeviceTypeMapper()
        {
            Table("device_type");
            Map(x => x.Id).Key(KeyType.Assigned);
            //Ignore this property entirely
            //optional, map all other columns
            AutoMap();
        }
    }
}
